<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="agency-header">
            <el-avatar :size="40" :src="formData.travelAgencyAvatar" />
            <span class="agency-name">{{ formData.travelAgencyName }}</span>
          </div>
          <div class="action-buttons">
            <el-button type="primary" @click="handleApprove" v-if="formData.auditStatus !== '通过'">通过审核</el-button>
            <el-button type="danger" @click="handleReject" v-if="formData.auditStatus !== '未通过'">拒绝审核</el-button>
            <el-button @click="goBack">返回列表</el-button>
          </div>
        </div>
      </template>

      <div class="info-container">
        <!-- 跟团游名称和状态 -->
        <div class="group-tour-header">
          <h2>{{ formData.groupTourName }}</h2>
          <el-tag :type="getStatusTagType(formData.auditStatus)">
            {{ formData.auditStatus }}
          </el-tag>
          <p class="register-time">发布日期: {{ formatTime(formData.releaseDate) }}</p>
        </div>

        <!-- 跟团游介绍 -->
        <div class="content-block" v-if="formData.groupTourIntroduction">
          <h4>跟团游介绍</h4>
          <div class="introduction-content" v-html="formData.groupTourIntroduction"></div>
        </div>

        <!-- 跟团游图片 -->
        <div class="content-block" v-if="images.length > 0">
          <h4>跟团游图片</h4>
          <div class="image-container">
            <el-carousel :interval="4000" type="card" height="200px">
              <el-carousel-item v-for="(image, index) in images" :key="index">
                <el-image style="width: 100%; height: 100%;" :src="image.groupTourImageLink"
                  :preview-src-list="previewImages" fit="cover" show-progress :preview-teleported="true"
                  :preview-class="'custom-preview-class'">
                  <template #toolbar="{ actions, prev, next, reset, activeIndex, setActiveItem }">
                    <el-icon @click="prev">
                      <ArrowLeft />
                    </el-icon>
                    <el-icon @click="next">
                      <ArrowRight />
                    </el-icon>
                    <el-icon @click="setActiveItem(previewImages.length - 1)">
                      <DArrowRight />
                    </el-icon>
                    <el-icon @click="actions('zoomOut')">
                      <ZoomOut />
                    </el-icon>
                    <el-icon @click="actions('zoomIn', { enableTransition: false, zoomRate: 2 })">
                      <ZoomIn />
                    </el-icon>
                    <el-icon @click="actions('clockwise', { rotateDeg: 180, enableTransition: false })">
                      <RefreshRight />
                    </el-icon>
                    <el-icon @click="actions('anticlockwise')">
                      <RefreshLeft />
                    </el-icon>
                    <el-icon @click="reset">
                      <Refresh />
                    </el-icon>
                    <el-icon @click="download(activeIndex)">
                      <Download />
                    </el-icon>
                  </template>
                </el-image>
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>

        <!-- 详细信息 -->
        <div class="content-block">
          <h4>详细信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="景点名称">{{ formData.scenicAreaName }}</el-descriptions-item>
            <el-descriptions-item label="所在省份">{{ formData.province }}</el-descriptions-item>
            <el-descriptions-item label="所在城市">{{ formData.city }}</el-descriptions-item>
            <el-descriptions-item label="负责人">{{ formData.principalName }}</el-descriptions-item>
            <el-descriptions-item label="负责人电话">{{ formData.principalPhone }}</el-descriptions-item>
            <el-descriptions-item label="负责人邮箱">{{ formData.principalEmail }}</el-descriptions-item>
            <el-descriptions-item label="开始日期">{{ formData.startDate }}</el-descriptions-item>
            <el-descriptions-item label="结束日期">{{ formData.endDate }}</el-descriptions-item>
            <el-descriptions-item label="集合时间">{{ formData.assemblyTime }}</el-descriptions-item>
            <el-descriptions-item label="集合地点">{{ formData.assemblyPlace }}</el-descriptions-item>
            <el-descriptions-item label="招募人数">{{ formData.recruitmentNumber }}</el-descriptions-item>
            <el-descriptions-item label="跟团金额">{{ formData.groupTourPrice }} 元</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import axios from 'axios'
import {
  ArrowLeft,
  ArrowRight,
  DArrowRight,
  Download,
  Refresh,
  RefreshLeft,
  RefreshRight,
  ZoomIn,
  ZoomOut,
} from '@element-plus/icons-vue'

export default {
  name: 'TravelAudit',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const loading = ref(false)
    const formData = ref({
      groupTourId: '',
      groupTourName: '',
      travelAgencyName: '',
      travelAgencyAvatar: '',
      scenicAreaName: '',
      province: '',
      city: '',
      principalName: '',
      principalPhone: '',
      principalEmail: '',
      startDate: '',
      endDate: '',
      assemblyTime: '',
      assemblyPlace: '',
      recruitmentNumber: 0,
      groupTourPrice: 0,
      groupTourIntroduction: '',
      releaseDate: '',
      auditStatus: '未审核'
    })
    const images = ref([])
    const previewImages = computed(() => images.value.map(img => img.groupTourImageLink))

    // 格式化时间显示
    const formatTime = (time) => {
      return dayjs(time).format('YYYY-MM-DD HH:mm')
    }

    // 获取状态标签类型
    const getStatusTagType = (status) => {
      switch (status) {
        case '通过': return 'success'
        case '未通过': return 'danger'
        case '未审核': return 'warning'
        default: return 'info'
      }
    }

    // 获取跟团游详情
    const fetchGroupTourDetail = async () => {
      try {
        loading.value = true;
        const id = route.params.id;

        if (!id || isNaN(Number(id))) {
          ElMessage.error('无效的团游ID');
          return;
        }

        const response = await axios.get(`/mw/travelAuditDetail/${id}`);
        formData.value = response.data;
      } catch (error) {
        ElMessage.error('获取详情失败: ' + error.message);
      } finally {
        loading.value = false;
      }
    };

    // 获取跟团游图片
    const fetchGroupTourImages = async () => {
      try {
        const id = route.params.id;
        if (!id || isNaN(Number(id))) {
          return;
        }
        const response = await axios.get(`/mw/travelAuditImages/${id}`);
        images.value = response.data;
      } catch (error) {
        console.error('获取图片失败:', error);
      }
    }

    // 通过审核
    const handleApprove = async () => {
      try {
        await ElMessageBox.confirm('确定通过该跟团游的审核吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        loading.value = true
        const response = await axios.post('/mw/approveTravelAudit', {
          id: formData.value.groupTourId
        })

        if (response.data > 0) {
          ElMessage.success('审核通过成功')
          formData.value.auditStatus = '通过'
        } else {
          ElMessage.error('审核操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('审核操作失败: ' + error.message)
        }
      } finally {
        loading.value = false
      }
    }

    // 拒绝审核
    const handleReject = async () => {
      try {
        await ElMessageBox.confirm('确定拒绝该跟团游的审核吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        loading.value = true
        const response = await axios.post('/mw/rejectTravelAudit', {
          id: formData.value.groupTourId
        })

        if (response.data > 0) {
          ElMessage.success('审核拒绝成功')
          formData.value.auditStatus = '未通过'
        } else {
          ElMessage.error('审核操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('审核操作失败: ' + error.message)
        }
      } finally {
        loading.value = false
      }
    }

    // 下载图片
    const download = (index) => {
      const url = previewImages.value[index]
      const suffix = url.slice(url.lastIndexOf('.'))
      const filename = Date.now() + suffix

      fetch(url)
        .then((response) => response.blob())
        .then((blob) => {
          const blobUrl = URL.createObjectURL(new Blob([blob]))
          const link = document.createElement('a')
          link.href = blobUrl
          link.download = filename
          document.body.appendChild(link)
          link.click()
          URL.revokeObjectURL(blobUrl)
          link.remove()
        })
    }

    // 返回列表
    const goBack = () => {
      router.push('/travel/list')
    }

    onMounted(() => {
      fetchGroupTourDetail()
      fetchGroupTourImages()
    })

    return {
      formData,
      loading,
      images,
      previewImages,
      formatTime,
      getStatusTagType,
      handleApprove,
      handleReject,
      goBack,
      download,
      ArrowLeft,
      ArrowRight,
      DArrowRight,
      Download,
      Refresh,
      RefreshLeft,
      RefreshRight,
      ZoomIn,
      ZoomOut,
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  max-width: 1000px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
}

.agency-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.agency-name {
  font-size: 16px;
  font-weight: bold;
}

.info-container {
  padding: 0 20px 20px;
}

.group-tour-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.group-tour-header h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.register-time {
  margin-top: 10px;
  color: #888;
  font-size: 14px;
}

/* 统一内容区块样式 */
.content-block {
  margin: 0 0 30px 0;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.content-block h4 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.introduction-content {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
  line-height: 1.6;
}

/* 详细信息表格调整 */
:deep(.el-descriptions) {
  width: 100%;
}

:deep(.el-descriptions__body) {
  background-color: #f9f9f9;
}

:deep(.el-descriptions__label) {
  width: 120px;
}

/* 图片容器 */
.image-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

/* 轮播图样式 */
:deep(.el-carousel) {
  margin: 0 auto;
  width: 100%;
}

:deep(.el-carousel__item) {
  background-color: #f5f7fa;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.el-carousel__item .el-image) {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .action-buttons {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    flex-wrap: wrap;
    gap: 10px;
  }

  .group-tour-header h2 {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .content-block {
    padding: 15px;
  }
}

/* 图片预览样式 */
:deep(.custom-preview-class) {
  width: 50% !important;
  height: 50% !important;
  max-width: 800px;
  max-height: 800px;
  margin: auto;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  position: fixed;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.custom-preview-class .el-image-viewer__wrapper) {
  width: 100%;
  height: 100%;
}

:deep(.custom-preview-class .el-image-viewer__img) {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
</style>